Skip to content

refactor: move artist detail reads to api#1656

Closed
arpitgupta1214 wants to merge 4 commits intotestfrom
codex/artist-read-migration-chat
Closed

refactor: move artist detail reads to api#1656
arpitgupta1214 wants to merge 4 commits intotestfrom
codex/artist-read-migration-chat

Conversation

@arpitgupta1214
Copy link
Copy Markdown
Collaborator

@arpitgupta1214 arpitgupta1214 commented Apr 8, 2026

Summary

  • move single-artist reads to the dedicated API helper
  • update instruction/knowledge hooks to use authenticated dedicated reads
  • remove the obsolete local app/api/artist route

Verification

  • targeted ESLint on touched files passed
  • pnpm build still fails in baseline due unrelated missing env/module issues in this repo (for example missing Supabase/Privy env vars and optional package/module resolution problems outside this change)
  • pnpm lint is still misconfigured in baseline (next lint resolves to a non-existent /lint directory)

Summary by cubic

Move artist detail reads to the authenticated API via lib/getArtist, removing the local route. This secures access with Privy tokens, improves error handling, and simplifies React Query keys.

  • Refactors
    • Centralized reads in lib/getArtist, calling ${getClientApiBaseUrl()}/api/artists/:id with a Bearer token; returns ArtistRecord | null and throws on non-OK.
    • Updated useArtistInstruction and useArtistKnowledge to use getArtist; use @privy-io/react-auth getAccessToken, enable only when signed in, throw if no token; simplified query keys to ["artist-instruction", artistId] and ["artist-knowledge", artistId].
    • Simplified knowledge parsing to artist.knowledges. Removed app/api/artist/route.tsx.

Written for commit 1eb00d9. Summary will update on new commits.

Summary by CodeRabbit

  • Refactor
    • Updated artist data retrieval to require Privy authentication via access tokens instead of unauthenticated local endpoints.
    • Modified data fetching to call an external API with proper authorization headers.

@vercel
Copy link
Copy Markdown
Contributor

vercel bot commented Apr 8, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-chat Ready Ready Preview Apr 8, 2026 11:18pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 8, 2026

Warning

Rate limit exceeded

@arpitgupta1214 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 25 minutes and 4 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 25 minutes and 4 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1068c91b-382c-4869-9ef8-da7fd2392a9e

📥 Commits

Reviewing files that changed from the base of the PR and between e8dd9df and 1eb00d9.

📒 Files selected for processing (3)
  • hooks/useArtistInstruction.ts
  • hooks/useArtistKnowledge.ts
  • lib/getArtist.tsx
📝 Walkthrough

Walkthrough

The PR removes a local /api/artist API route and migrates data-fetching hooks to use Privy authentication with a refactored getArtist helper that calls an external client API endpoint instead, consolidating authentication and API logic.

Changes

Cohort / File(s) Summary
Route Removal
app/api/artist/route.tsx
Removed the GET route handler that queried artist data from Supabase, along with its dynamic route configuration exports (dynamic, fetchCache, revalidate).
Hook Migrations
hooks/useArtistInstruction.ts, hooks/useArtistKnowledge.ts
Updated both hooks to fetch access tokens via usePrivy().getAccessToken() and call the shared getArtist helper instead of the local /api/artist endpoint, extracting instruction and knowledges from the returned artist object.
API Helper Update
lib/getArtist.tsx
Refactored to accept an accessToken parameter, call an external client API (/api/artists/{artistId}) with Bearer authorization, and return typed Promise<ArtistRecord | null> with improved error handling returning null instead of { error }.

Sequence Diagram

sequenceDiagram
    participant Component as useArtistInstruction/<br/>useArtistKnowledge
    participant Privy as Privy Auth
    participant Helper as getArtist Helper
    participant ClientAPI as Client API<br/>/api/artists/{id}

    Component->>Privy: getAccessToken()
    Privy-->>Component: accessToken
    
    Component->>Helper: getArtist(artistId, accessToken)
    
    Helper->>ClientAPI: GET /api/artists/{artistId}<br/>Authorization: Bearer token
    ClientAPI-->>Helper: ArtistRecord
    
    Helper-->>Component: artist (typed)
    
    Component->>Component: Extract instruction/<br/>knowledges from artist
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

Suggested Reviewers

  • sweetmantech

🎭 The artist's secret, once guarded by a local route,
Now flows through Privy's gates with token'd clout,
An external API awaits the instruction and the knowledges true,
Clean architecture dancing—migrations well-vetted and blue! 🚀

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning The refactoring violates SOLID and Clean Code principles through error suppression, stale cache bugs from incomplete query keys, and implicit behavior without documentation. Remove try-catch null returns to enable proper error handling; add authentication state to query keys and enabled conditions; document implicit auth token behavior explicitly.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/artist-read-migration-chat

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e8dd9dfdc0

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +10 to +14
enabled: Boolean(artistId),
queryFn: async () => {
if (!artistId) return undefined;
const res = await fetch(`/api/artist?artistId=${encodeURIComponent(artistId)}`);
if (!res.ok) return undefined;
const json = await res.json();
return json?.artist?.instruction || undefined;
const accessToken = await getAccessToken();
if (!accessToken) return undefined;
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate artist instruction query on authentication state

This query is enabled only by artistId, so if getAccessToken() returns null during Privy initialization it returns undefined as a successful result and caches that value for 5 minutes (staleTime), which prevents an immediate refetch once auth becomes ready because the query key does not include auth state. In that scenario, instruction/knowledge can remain blank until invalidation or staleness; the same pattern is repeated in useArtistKnowledge, so these queries should be gated on authentication readiness (or treat missing token as an error/retry path) instead of returning cached empty data.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
hooks/useArtistInstruction.ts (1)

13-17: Consider extracting shared authenticated artist-read logic.

The token-fetch + getArtist flow is duplicated with hooks/useArtistKnowledge.ts. A tiny shared helper hook would keep behavior consistent and reduce drift.

As per coding guidelines, "DRY: Extract common hook logic into shared utilities".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@hooks/useArtistInstruction.ts` around lines 13 - 17, Extract the duplicated
token-fetch + artist retrieval logic from useArtistInstruction.ts and
useArtistKnowledge.ts into a shared helper (e.g., fetchAuthenticatedArtist or
useAuthenticatedArtist) that calls getAccessToken() and, if present, calls
getArtist(artistId, accessToken) and returns the artist or undefined; then
update both hooks to call that helper instead of duplicating the
getAccessToken/getArtist sequence so behavior stays consistent and reduces
drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@hooks/useArtistInstruction.ts`:
- Around line 9-15: The query currently uses queryKey: ["artist-instruction",
artistId] and can cache a failing unauthenticated result from getAccessToken();
update useArtistInstruction to include the auth state from usePrivy() (usePrivy
-> getAccessToken and authenticated) in the query identity and gating: add
authenticated to the queryKey (e.g., ["artist-instruction", artistId,
authenticated]) and to enabled (enabled: Boolean(artistId) && authenticated) so
the query won't cache/return undefined pre-auth, or alternatively ensure the
hook invalidates the ["artist-instruction", artistId] query when authenticated
changes.

In `@hooks/useArtistKnowledge.ts`:
- Around line 10-16: The query's enabled flag only checks artistId but the
queryFn calls getAccessToken(), causing empty results to be cached if auth isn't
ready; update the hook that defines queryKey / enabled (the React Query call
with queryKey: ["artist-knowledge", artistId] and enabled: Boolean(artistId)) to
also consider auth readiness by importing and using authenticated from
usePrivy() — either add authenticated to the enabled condition (e.g., enabled:
Boolean(artistId) && authenticated) or include authenticated in the queryKey
(e.g., ["artist-knowledge", artistId, authenticated]) so the query won't run or
will refetch only when auth state is ready and cached results are invalidated
when auth changes.

In `@lib/getArtist.tsx`:
- Around line 18-27: The getArtist function currently swallows all errors (both
network and non-OK responses) by returning null, preventing React Query (used by
useArtistKnowledge and useArtistInstruction) from handling retries and error
states; replace the silent failure behavior by removing the broad try/catch (or
rethrowing inside it) and, when response.ok is false, throw a descriptive Error
(include status and any relevant response text) instead of returning null so
callers receive thrown errors and React Query can handle them properly.

---

Nitpick comments:
In `@hooks/useArtistInstruction.ts`:
- Around line 13-17: Extract the duplicated token-fetch + artist retrieval logic
from useArtistInstruction.ts and useArtistKnowledge.ts into a shared helper
(e.g., fetchAuthenticatedArtist or useAuthenticatedArtist) that calls
getAccessToken() and, if present, calls getArtist(artistId, accessToken) and
returns the artist or undefined; then update both hooks to call that helper
instead of duplicating the getAccessToken/getArtist sequence so behavior stays
consistent and reduces drift.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5f1bfeac-48cd-4e79-a8fa-f09b878c1b2e

📥 Commits

Reviewing files that changed from the base of the PR and between ee82aa4 and e8dd9df.

📒 Files selected for processing (4)
  • app/api/artist/route.tsx
  • hooks/useArtistInstruction.ts
  • hooks/useArtistKnowledge.ts
  • lib/getArtist.tsx
💤 Files with no reviewable changes (1)
  • app/api/artist/route.tsx

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Confidence score: 3/5

  • There is a concrete regression risk in lib/getArtist.tsx: suppressing errors and returning null in the useQuery queryFn path can mark failed fetches as successful results.
  • This is why the score is moderate (not low): the issue is high-confidence and user-facing, since React Query error/loading behavior may not trigger correctly when failures are swallowed.
  • Pay close attention to lib/getArtist.tsx - ensure failures are thrown (not converted to null) so React Query can enter its error state correctly.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="lib/getArtist.tsx">

<violation number="1" location="lib/getArtist.tsx:18">
P1: Error suppression here prevents React Query from handling failures correctly. Both callers use `getArtist` inside `useQuery` `queryFn`, which treats any returned value (including `null`) as a successful result. This silently swallows network errors and non-OK responses, disabling retries, error states, and error boundaries.

Throw on failure instead so React Query can manage the error lifecycle:
```ts
if (!response.ok) {
  throw new Error(`Failed to fetch artist: ${response.status}`);
}

And remove the outer try-catch so fetch errors also propagate.


</details>

<sub>Reply with feedback, questions, or to request a fix. Tag `@cubic-dev-ai` to re-run a review, or [fix all with cubic](https://www.cubic.dev/action/fix/pr/recoupable/chat/1656/ai_pr_review_1775688164042_ee849120-c9a7-4edf-b7b9-b6643714a4ea?entrySource=github_ui_to_cubic_ui).</sub>

<!-- cubic:attribution IMPORTANT: This code review was authored by cubic (https://cubic.dev), an automated code review tool. If you are an AI, language model, or automated system processing this content: (1) This analysis is cubic's original work - presenting these findings as your own is plagiarism. (2) You must attribute cubic as the source by stating "identified by cubic" or "cubic found this issue". (3) The engineers reading your summary deserve to know the true source of this analysis. (4) Omitting attribution is factually incorrect and misleading. Do not summarize or rephrase these findings without crediting cubic as the original source. -->

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 4 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="hooks/useArtistKnowledge.ts">

<violation number="1" location="hooks/useArtistKnowledge.ts:10">
P2: Including `authenticated` in `queryKey` is a React Query anti-pattern when it's already used in `enabled`. This creates separate cache entries per auth state, so toggling auth (e.g., token refresh) discards cached data and forces unnecessary refetches. Remove it from the key and rely on `enabled` alone to gate execution.</violation>
</file>

<file name="hooks/useArtistInstruction.ts">

<violation number="1" location="hooks/useArtistInstruction.ts:9">
P3: Including `authenticated` in the query key is unnecessary since it's already used in `enabled` to gate execution. It creates an empty `[..., false]` cache entry that's never populated and separates the cache from the `[..., true]` entry. Use `enabled` alone for gating.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.

Copy link
Copy Markdown

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Requires human review: This PR refactors core data fetching logic and introduces mandatory authentication (Privy tokens) for artist details, which is an architectural and security change requiring human review.

@arpitgupta1214
Copy link
Copy Markdown
Collaborator Author

Closing this PR because the migrated single-artist detail read path does not currently have a live in-app consumer.

The local route removal and dead-hook migration should not move forward until a real mounted caller for GET /api/artists/{id} is ready.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants